package client;

import lovedna.math.Color;
import lovedna.math.Quaternion;
import lovedna.Debug;
import lovedna.ds.FastArray;
import lovedna.utils.ai.AStarNode;
import lovedna.utils.ai.AStarResult;
import lovedna.utils.ai.AStarGrid;
import haxe.macro.Compiler.IncludePosition;
import lovedna.math.Vector3;
import lovedna.utils.L;
import lovedna.math.Vector2;
import lovedna.format.animation.IAnimation;
import lovedna.ds.Array2D;
class MapData {
    public static inline var empty:Int=0;
    public static inline var temp:Int=1;
    public static inline var block:Int=2;
    private var offset:Vector3;
    private var _data:Array2D<Int>;
    private var _size:Vector2;
    private var _temp:Array<Int>;
    private var _pos:Vector3;


    private var _astar:AStarGrid;

    private var _list:FastArray<AStarNode>;

    public function new(width:Int,height:Int,size:Vector2) {
        _data=new Array2D<Int>(width,height);
        _size=new Vector2();
        _size.copy(size);
        _temp=[];
        _pos=new Vector3();
        offset=new Vector3(size.x*0.5,0,size.y*0.5);
        _astar=new AStarGrid(width,height,false);
		_list=[];
    }
    public function toXY(id:Int) {
        var fx=_data.getX(id);
        var fy=_data.getY(id);
        var fnode=_astar.getNode(fx,fy);
        trace(fnode.positoin);
    }
    public function random() {
        var x:Int=L.rangeInt(0,_data.width);
        _data.getListByX(x,_temp);
        var len=_data.height;
        while (len-- > 0){
            var y:Int=L.rangeInt(0,len+1);
            if(_astar.getNode(x,y).walkable){
                return _astar.getNode(x,y);
            }
        }
        return null;
    }
    public function searchPath(from:AStarNode,to:AStarNode) {
        _astar.set(from,to);
        if(_astar.search()==AStarResult.success){
            return _astar.getPath();
        }
        return null;
    }
    public function set(id:Int) {
        var fx=_data.getX(id);
        var fy=_data.getY(id);
        var fnode=_astar.getNode(fx,fy);
        if(!fnode.walkable)return false;
        fnode.walkable=false;
        return true;
    }
    public function getNode(id:Int) {
        var x=_data.getX(id);
        var y=_data.getY(id);
        return _astar.getNode(x,y);
    }
    public function getPosition(node:AStarNode) {
        _pos.set(node.positoin.x*_size.x,0,node.positoin.y*_size.y).add(offset);
        return _pos;
    }
    public function draw(offset:Vector3) {
        // return;
        var len=_list.length;
        var q:Quaternion=Quaternion.instance;
        q.setEulerAngles(90,0,0);
		var w = _data.width;
		var h = _data.height;
		for (i in 0...w) {
			for (j in 0...h) {
				var node = _astar.getNode(i, j);
				var pos = getPosition(node).add(offset);
				Debug.drawPlane(pos, Vector3.right, Vector3.forward, node.walkable?Color.GREEN:Color.RED);
			}
		}
    }
}
